package com.mianyang.zhangsan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mianyang.zhangsan.common.util.CommonUtils;
import com.mianyang.zhangsan.model.dto.SecGrant;
import com.mianyang.zhangsan.model.dto.SecGrantAuthDto;
import com.mianyang.zhangsan.model.entity.SecRoleAuthority;
import com.mianyang.zhangsan.mapper.SecRoleAuthorityMapper;
import com.mianyang.zhangsan.service.ISecRoleAuthorityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author jiangjr
 * @since 2022-10-23
 */
@Service
public class SecRoleAuthorityServiceImpl extends ServiceImpl<SecRoleAuthorityMapper, SecRoleAuthority> implements ISecRoleAuthorityService {

    @Override
    public List<Long> selectAuthorities(Long roleId) {
        QueryWrapper<SecRoleAuthority> wrapper = new QueryWrapper<>();
        if (roleId != null) {
            wrapper.eq("role_id", roleId);
            return convert(list(wrapper));
        }
        return null;
    }

    @Override
    public List<Long> selectAuthorities(List<Long> roleIds) {
        QueryWrapper<SecRoleAuthority> wrapper = new QueryWrapper<>();
        if (roleIds != null && roleIds.size() > 0) {
            wrapper.in("role_id", roleIds);
            return convert(list(wrapper));
        }
        return null;
    }

    @Override
    public void grant(SecGrant grant) {
        // 删除存在的关系
        QueryWrapper<SecRoleAuthority> wrapper = new QueryWrapper<>();
        Long relationId = grant.getRelationId();
        if (relationId != null) {
            wrapper.eq("role_id", relationId);
            remove(wrapper);
            // 新增关系
            List<Long> relations = grant.getRelations();
            if (CommonUtils.isNotEmpty(relations)) {
                List<SecRoleAuthority> roleAuthorities = relations.stream().map(auth -> SecRoleAuthority.builder().authorityId(auth).roleId(relationId).build()).collect(Collectors.toList());
                saveBatch(roleAuthorities);
            }
        }

    }

    @Override
    public void removeByRoleId(Long roleId) {
        QueryWrapper<SecRoleAuthority> wrapper = new QueryWrapper<>();
        if (roleId != null) {
            wrapper.eq("role_id", roleId);
            remove(wrapper);
        }
    }

    private List<Long> convert(List<SecRoleAuthority> authorities) {
        if (authorities == null || authorities.size() <= 0) {
            return null;
        }
        return authorities.stream()
                .map(SecRoleAuthority::getAuthorityId)
                .collect(Collectors.toList());
    }
}
